import os
import re
import logging
from pathlib import Path
from moviepy import VideoFileClip

import pandas as pd
from pandas import Series

import common.utils
# from tools import _get_files_name as get_files_name
from tools import merge_student_dataframes
from tools import convert_mmdd_to_date
from common import utils
from file import get_files_name
from file import has_duplicates

文档 = '([^-\.]+)'
班级 = '([^-\.]+)'
学号 = '([0-9]{11})'
姓名 = '([^-\.]+)'
日期 = '([0-9]{4})'
时长 = '([0-9]+)'
后缀 = '([^-\.]+)'

BASE_PATH = r"D:\100-Project\2025-2026-1学期安排\首义学院\19201017_《企业级应用开发课程设计（企业）》"
FOLDER_PATH = f"{BASE_PATH}\学生提交\视频"
FILE_TYPES = ['.mp4', '.mkv']
PATTERN_视频_0 = f'^{班级}-{学号}-{姓名}.{后缀}$'
PATTERN_视频_1 = f'^{班级}-{学号}-{姓名}.{日期}.{后缀}$'
PATTERN_视频_2 = f'^{班级}-{学号}-{姓名}.{日期}_{时长}.{后缀}$'

se_filenames = pd.Series()


def load_filenames():
    global se_filenames
    try:
        # 验证文件夹是否存在
        if not os.path.isdir(FOLDER_PATH):
            logging.error(f"文件夹不存在 - {FOLDER_PATH}")
            return pd.Series([], name='文件名')

        folder = Path(FOLDER_PATH)
        matched_files = []
        file_types = [ext.lower() for ext in FILE_TYPES]  # 统一小写处理

        # 收集所有匹配的文件
        for item in folder.iterdir():
            if item.is_file() and item.suffix.lower() in file_types:
                # 根据返回类型处理路径
                matched_files.append(item.name)

        # 按文件名排序
        matched_files.sort()

        logging.debug(f"在 {FOLDER_PATH} 中找到 {len(matched_files)} 个 {FILE_TYPES} 文件")

        se_filenames = pd.Series(matched_files, name='文件名')
    except Exception as e:
        logging.error(f"获取文件列表时出错: {str(e)}")
        return pd.Series([], name='文件名')


def check_filenames_format():
    logging.debug("检查视频文件名是否符合规则")
    global se_filenames
    invalid_strings = []
    for s in se_filenames:
        if bool(re.match(PATTERN_视频_2, s)):
            continue
        elif not bool(re.match(PATTERN_视频_1, s)):
            continue
        elif not bool(re.match(PATTERN_视频_0, s)):
            continue
        else:
            invalid_strings.append(s)

    if invalid_strings:
        logging.debug("以下字符串不符合格式要求:")
        for s in invalid_strings:
            logging.debug(f"  - {s}")
        logging.error(f"\n❌ 总计: {len(invalid_strings)} 个字符串不符合规则")
        exit(0)
    else:
        logging.info("✅ 所有字符串都符合格式要求!")


def check_filenames_duplicates():
    logging.info('检查报告文件名是否有重复')
    global se_filenames
    # 去掉后缀再判断重复
    new_se = se_filenames.str.rsplit('.', n=1).str[0]

    # 计算每个值的出现次数
    value_counts = new_se.value_counts()

    # 找出重复项（出现次数大于1）
    duplicates = value_counts[value_counts > 1]

    if not duplicates.empty:
        logging.info(f"列表中有 {len(duplicates)} 个重复项:")
        for i, (value, count) in enumerate(duplicates.items(), 1):
            logging.info(f"{i}. {value} (出现次数: {count})")
        logging.error('报告文件名有重复')
        exit(0)
    else:
        logging.info('✅ 报告文件名无重复')


def rename_filenames():
    logging.info('为视频文件名添加时长信息')
    global se_filenames

    folder = Path(FOLDER_PATH)
    file_types = [ext.lower() for ext in FILE_TYPES]  # 统一小写处理

    for item in folder.iterdir():
        if item.is_file() and (item.suffix.lower() in file_types):
            __rename_filename(item.name)


def __rename_filename(filename: str):
    if bool(re.match(PATTERN_视频_2, filename)):
        # logging.debug(f'文件 {filename} 已含时长')
        pass
    elif bool(re.match(PATTERN_视频_1, filename)) or bool(re.match(PATTERN_视频_0, filename)):
        logging.info(f'文件 {filename} 缺时长')
        duration = __get_video_duration(f'{FOLDER_PATH}/{filename}')
        # region 为文件添加时长后缀
        old_path = Path(f'{FOLDER_PATH}/{filename}')

        # 获取文件名（不含目录）
        file_name = old_path.name
        # 查找最后一个'.'的位置
        last_dot_index = file_name.rfind('.')

        # 在最后一个'.'前插入字符串
        new_file_name = f"{file_name[:last_dot_index]}_{duration}{file_name[last_dot_index:]}"

        # 构建新文件的完整路径
        new_path = old_path.parent / new_file_name
        # 检查新路径是否已存在
        if new_path.exists():
            print(f"错误：目标文件已存在 - {new_path}")
            exit(0)

        # 执行重命名
        try:
            old_path.rename(new_path)
            print(f"重命名成功：{old_path} -> {new_path}")
        except Exception as e:
            print(f"重命名失败：{str(e)}")
            exit(0)
        # endregion
    else:
        print(f'文件 {filename} 格式错误')
        exit(0)


def __get_video_duration(file_path):
    try:
        with VideoFileClip(file_path) as video:
            duration = video.duration  # 时长（秒）
            return round(duration)
    except Exception as e:
        print(f"错误：{e}")
        return None


if __name__ == "__main__":
    load_filenames()
    check_filenames_format()
    check_filenames_duplicates()
    rename_filenames()
